<template>
  <div class="printer-management">
    <!-- 搜索和操作区域 -->
    <div class="operation-bar">
      <el-input
          v-model="search.query"
          placeholder="输入关键字搜索"
          style="width: 300px; margin-right: 15px"
          clearable
      />
      <el-select
          v-model="search.status"
          placeholder="选择状态"
          style="width: 200px; margin-right: 15px"
          clearable
      >
        <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        />
      </el-select>

      <el-button type="success" @click="handleBatchSearch">
        搜索
      </el-button>
      <el-button type="info" @click="handleAddPrinter">新增设备</el-button>
      <el-button type="danger" @click="handleBatchDelete">批量删除</el-button> <!-- 添加批量删除按钮 -->
    </div>

    <!-- 数据表格 -->
    <el-table
        :data="printers"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        border
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="编号" width="100" sortable />
      <el-table-column prop="deviceName" label="设备名称" width="150" />
      <el-table-column prop="receiptType" label="小票类型" width="120" />
      <el-table-column prop="printerType" label="打印机类型" width="130" />
      <el-table-column prop="deviceBrand" label="设备品牌" width="120" />
      <el-table-column prop="deviceSn" label="设备SN号" width="180" />
      <el-table-column prop="deviceKey" label="设备Key" width="200" />
      <el-table-column prop="receiptSpec" label="小票规格" width="150" />
      <el-table-column prop="storeName" label="所属门店" width="150" />
      <el-table-column label="状态" width="120">
        <template #default="{ row }">
          <el-switch
              v-model="row.status"
              active-value="1"
              inactive-value="0"
              disabled= false
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          :page-size="pageSize"
          :total="total"
          :current-page="pageNum"
          layout="prev, pager, next"
          @current-change="handlePageChange"
      />
    </div>

    <!-- 新增/编辑设备弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="50%"
        @close="handleDialogClose"
    >
      <el-form :model="form" label-width="120px">
        <el-form-item label="设备名称">
          <el-input v-model="form.deviceName" />
        </el-form-item>
        <el-form-item label="小票类型">
          <el-input v-model="form.receiptType" />
        </el-form-item>
        <el-form-item label="打印机类型">
          <el-input v-model="form.printerType" />
        </el-form-item>
        <el-form-item label="设备品牌">
          <el-input v-model="form.deviceBrand" />
        </el-form-item>
        <el-form-item label="设备SN号">
          <el-input v-model="form.deviceSn" />
        </el-form-item>
        <el-form-item label="设备Key">
          <el-input v-model="form.deviceKey" />
        </el-form-item>
        <el-form-item label="小票规格">
          <el-input v-model="form.receiptSpec" />
        </el-form-item>
        <el-form-item label="所属门店">
          <el-input v-model="form.storeName" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
              v-model="form.status"
              active-value="1"
              inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import axios from "axios";
import {ElMessage} from "element-plus";

// 分页参数
const pageNum = ref(1);
const pageSize = ref(5);
const total = ref(0);

// 数据
const printers = ref([]);

// 获取所有数据
const getAllPrinters =  () => {
  axios.post(`device/getDeviceInfoByNameSN/${pageNum.value}/${pageSize.value}`, search.value).then(response => {
    printers.value = response.data.obj.data
    total.value = response.data.obj.total
  })
}

// 搜索对象
const search = ref({})

// 删除数组
const deletes = ref([])

// 选择功能
const selectedPrinters = ref([])
const handleSelectionChange = (selection) => {
  selectedPrinters.value = selection
}

// 批量操作
const handleBatchEnable = () => {
  selectedPrinters.value.forEach(printer => printer.status = '1')
}

const handleBatchDisable = () => {
  selectedPrinters.value.forEach(printer => printer.status = '0')
}

// 批量删除操作
const handleBatchDelete = () => {
  if (selectedPrinters.value.length === 0) {
    ElMessage.warning('请选择要删除的设备');
    return;
  }

  deletes.value = selectedPrinters.value.map(printer => printer.id);

  try {
    axios.post(`device/deleteDeviceInfo`, deletes.value);
    deletes.value = [];
    getAllPrinters();
    ElMessage.success('删除成功');
  } catch (error) {
    ElMessage.error('删除失败');
  }
}

// 搜索操作
const handleBatchSearch = () => {
  // 搜索逻辑
  getAllPrinters();
}

// 其他操作
const handleAddPrinter = () => {
  dialogTitle.value = '新增设备';
  form.id = '';
  form.deviceName = '';
  form.receiptType = '';
  form.printerType = '';
  form.deviceBrand = '';
  form.deviceSn = '';
  form.deviceKey = '';
  form.receiptSpec = '';
  form.storeName = '';
  form.status = '1';
  dialogVisible.value = true;
}

const handleEdit = (printer) => {
  dialogTitle.value = '编辑设备';
  form.id = printer.id;
  form.deviceName = printer.deviceName;
  form.receiptType = printer.receiptType;
  form.printerType = printer.printerType;
  form.deviceBrand = printer.deviceBrand;
  form.deviceSn = printer.deviceSn;
  form.deviceKey = printer.deviceKey;
  form.receiptSpec = printer.receiptSpec;
  form.storeName = printer.storeName;
  form.status = printer.status;
  dialogVisible.value = true;
}

// 删除操作
const handleDelete = (id) => {
  deletes.value.push(id);
  try {
    console.log(deletes.value);
    axios.post(`device/deleteDeviceInfo`, deletes.value)
    deletes.value = [];
    getAllPrinters();

    ElMessage.success('删除成功')
  } catch (error) {
    ElMessage.error('删除失败');
  }
}

// 分页事件处理
const handlePageChange = (newPage) => {
  pageNum.value = newPage;
  getAllPrinters();
}

// 页面加载时获取数据
onMounted(() => {
  getAllPrinters();
})

// 状态选项
const statusOptions = ref([
  { label: '启用', value: '1' },
  { label: '禁用', value: '0' }
])

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref('');
const form = reactive({
  id: '',
  deviceName: '',
  receiptType: '',
  printerType: '',
  deviceBrand: '',
  deviceSn: '',
  deviceKey: '',
  receiptSpec: '',
  storeName: '',
  status: '1'
});

const handleDialogClose = () => {
  // 清空表单数据
  form.id = '';
  form.deviceName = '';
  form.receiptType = '';
  form.printerType = '';
  form.deviceBrand = '';
  form.deviceSn = '';
  form.deviceKey = '';
  form.receiptSpec = '';
  form.storeName = '';
  form.status = '1';
}

const handleSave = async () => {
  if (form.id) {
    // 编辑设备
    try {
      await axios.post(`device/editDeviceInfo`, form);
      const updatedPrinterIndex = printers.value.findIndex(printer => printer.id === form.id);
      if (updatedPrinterIndex !== -1) {
        printers.value[updatedPrinterIndex] = { ...form };
      }
      dialogVisible.value = false;
      ElMessage.success("设备信息更新成功")
    } catch (error) {
      ElMessage.success("设备信息更新失败")
    }
  } else {
    // 新增设备
    try {
      const response = await axios.post('device/addDeviceInfo', form);
      getAllPrinters();
      dialogVisible.value = false;
    } catch (error) {
      console.error("新增设备信息失败:", error);
    }
  }
}
</script>

<style scoped>
.printer-management {
  padding: 20px;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 20px;
}

.el-button + .el-button {
  margin-left: 8px;
}
</style>
